package com.djl.springcloud.alibaba.controller;

import com.djl.springcloud.entities.CommonResult;
import com.djl.springcloud.entities.Payment;
import com.djl.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @program: cloud2020
 * @description:
 * @author: Mr.dai
 * @create: 2021-09-16 21:13
 **/
//这个注释决定了返回json字符串，记得每次都要加
@RestController
@Slf4j
public class PaymentController {
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private  String serverPort;



    @PostMapping(value = "/payment/create")
    public CommonResult create(@RequestBody Payment payment){
        int result = paymentService.create(payment);
        log.info("***插入结果***:"+result);
        if (result>0){
            return new CommonResult(200,"插入数据成功"+serverPort,result);
        }else {
            return new CommonResult(444,"插入数据失败"+serverPort,null);
        }
    }

    @GetMapping(value = "/payment/get/{id}")
    public CommonResult getPaymentId(@PathVariable("id") Long id){
        Payment payment = paymentService.getPaymentId(id);
        if (payment!=null){
            return new CommonResult(200,"查询成功"+serverPort,payment);
        }else {
            return new CommonResult(444,"没有对应记录,查询id使"+id,null);
        }
    }

    @GetMapping(value = "/payment/discovery/{serviceId}")
    public Object discovery(@PathVariable("serviceId") String serviceId){

        //获取服务清单列表
        List<String> services = discoveryClient.getServices();
        for (String element : services){
            log.info("***element"+element);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
        for (ServiceInstance instance : instances){
            log.info("***getHost"+instance.getHost());
            log.info("***getInstanceId"+instance.getInstanceId());
            log.info("***getScheme"+instance.getScheme());
            log.info("***getMetadata"+instance.getMetadata());
            log.info("***getPort"+instance.getPort());
            log.info("***getUri"+instance.getUri());
            log.info("***getClass"+instance.getClass());
        }
                return this.discoveryClient;
    }
    @GetMapping(value = "/payment/feign/timeout")
    public String paymentFeignTimeout(){
        try { TimeUnit.SECONDS.sleep(3); }catch (Exception e) {e.printStackTrace();}
        return serverPort;
    }


}
